package com.runningboy.es_demo.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Description: 添加ES的开发包TransportClient到springboot中管理起来
 * @Author Runningboy
 * @Date 2020/6/26 14:17
 * @Version 1.0
 */
@Configuration
public class ESConfig {

    /**
     * 用TransportClient构造ES的client，后续ES相关的开发都是围绕这个client进行
     * @return
     * @throws UnknownHostException
     */
    @Bean
    public TransportClient esClient() throws UnknownHostException {
        //创建ES节点，配置IP和TCP端口
        InetSocketTransportAddress masterNode = new InetSocketTransportAddress(
                InetAddress.getByName("localhost"),
                9300
        );
        //TODO 如果有从节点，可以类似上面这样继续创建和配置


        //初始化ES配置
        Settings settings = Settings.builder()
                .put("cluster.name","runningboy")
                .build();

        TransportClient esClient = new PreBuiltTransportClient(settings);
        //将节点添加到ES集群服务中
        esClient.addTransportAddress(masterNode);

        return esClient;
    }

}
